<?php

namespace common\models\batch;

use common\models\File;
use yii\base\Model;
use Yii;

class FileBatch extends Model
{
    public $batch;

    public $doBatch;

    public $id;

    public function rules()
    {
        return [
            [['batch', 'doBatch', 'id'], 'required'],
            ['batch', 'in', 'range' => ['delete']],
            ['id', 'isIds'],
        ];
    }

    public function isIds($attribute, $params)
    {
        $value = $this->$attribute;
        if (!is_array($value)) {
            $this->addError('id', 'id invalid');
        }
    }

    public function process($id, $data)
    {
        $this->id = $id;

        if (!$this->load($data) || !$this->validate()) {
            return false;
        }

        if ($this->batch == 'delete' && $this->doBatch) {
            $count = 0;
            foreach ($this->id as $id) {
                $file = File::findOne($id);
                if ($file && $file->bundle == File::className()) {
                    $file->delete() && $count++;
                }
            }
            return '已删除' . $count . '个文件。';
        }
        return true;
    }
}
